#!/usr/bin/env node
/**
 * 开发环境助手 MCP 服务器
 * 提供实时环境监控、代码分析、自动修复和优化建议
 */

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
    CallToolRequestSchema,
    ErrorCode,
    ListToolsRequestSchema,
    McpError,
} from '@modelcontextprotocol/sdk/types.js';
import fs from 'fs/promises';
import { exec } from 'child_process';
import { promisify } from 'util';
import os from 'os';
import path from 'path';

const execAsync = promisify(exec);

class DevAssistantServer {
    constructor() {
        this.server = new Server(
            {
                name: 'dev-assistant-server',
                version: '0.1.0',
            },
            {
                capabilities: {
                    tools: {},
                },
            }
        );

        this.setupToolHandlers();

        // 错误处理
        this.server.onerror = (error) => console.error('[MCP Error]', error);
        process.on('SIGINT', async () => {
            await this.server.close();
            process.exit(0);
        });
    }

    setupToolHandlers() {
        this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
            tools: [
                {
                    name: 'monitor_system',
                    description: '监控系统资源使用情况，包括CPU、内存、磁盘等',
                    inputSchema: {
                        type: 'object',
                        properties: {},
                        required: [],
                    },
                },
                {
                    name: 'analyze_dependencies',
                    description: '分析项目依赖，检查过时的包、安全漏洞等',
                    inputSchema: {
                        type: 'object',
                        properties: {
                            project_path: {
                                type: 'string',
                                description: '项目路径',
                            },
                            package_manager: {
                                type: 'string',
                                description: '包管理器（npm、pip等）',
                                enum: ['npm', 'pip', 'yarn', 'auto'],
                            },
                        },
                        required: ['project_path'],
                    },
                },
                {
                    name: 'analyze_code',
                    description: '分析代码质量，检查潜在问题',
                    inputSchema: {
                        type: 'object',
                        properties: {
                            file_path: {
                                type: 'string',
                                description: '文件或目录路径',
                            },
                            language: {
                                type: 'string',
                                description: '编程语言',
                                enum: ['javascript', 'python', 'typescript', 'auto'],
                            },
                        },
                        required: ['file_path'],
                    },
                },
                {
                    name: 'optimize_imports',
                    description: '优化代码导入，删除未使用的导入，整理导入顺序',
                    inputSchema: {
                        type: 'object',
                        properties: {
                            file_path: {
                                type: 'string',
                                description: '文件路径',
                            },
                            language: {
                                type: 'string',
                                description: '编程语言',
                                enum: ['javascript', 'python', 'typescript', 'auto'],
                            },
                        },
                        required: ['file_path'],
                    },
                },
                {
                    name: 'check_network',
                    description: '检查网络连接状态',
                    inputSchema: {
                        type: 'object',
                        properties: {
                            target: {
                                type: 'string',
                                description: '目标URL或IP（可选）',
                            },
                        },
                        required: [],
                    },
                },
            ],
        }));

        this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
            const { name, arguments: args } = request.params;

            try {
                switch (name) {
                    case 'monitor_system':
                        return await this.monitorSystem();
                    case 'analyze_dependencies':
                        return await this.analyzeDependencies(args.project_path, args.package_manager || 'auto');
                    case 'analyze_code':
                        return await this.analyzeCode(args.file_path, args.language || 'auto');
                    case 'optimize_imports':
                        return await this.optimizeImports(args.file_path, args.language || 'auto');
                    case 'check_network':
                        return await this.checkNetwork(args.target);
                    default:
                        throw new McpError(
                            ErrorCode.MethodNotFound,
                            `未知工具: ${name}`
                        );
                }
            } catch (error) {
                if (error instanceof McpError) {
                    throw error;
                }

                return {
                    content: [
                        {
                            type: 'text',
                            text: `执行错误: ${error.message}`,
                        },
                    ],
                    isError: true,
                };
            }
        });
    }

    async monitorSystem() {
        // 获取系统信息
        const cpuInfo = os.cpus();
        const totalMem = os.totalmem();
        const freeMem = os.freemem();
        const usedMem = totalMem - freeMem;
        const memUsage = (usedMem / totalMem * 100).toFixed(2);

        // 获取磁盘信息
        let diskInfo;
        try {
            if (process.platform === 'win32') {
                const { stdout } = await execAsync('wmic logicaldisk get size,freespace,caption');
                diskInfo = `磁盘信息:\n${stdout}`;
            } else {
                const { stdout } = await execAsync('df -h');
                diskInfo = `磁盘信息:\n${stdout}`;
            }
        } catch (error) {
            diskInfo = `无法获取磁盘信息: ${error.message}`;
        }

        // 获取进程信息
        let processInfo;
        try {
            if (process.platform === 'win32') {
                const { stdout } = await execAsync('tasklist /FI "MEMUSAGE gt 100000"');
                processInfo = `内存占用较高的进程:\n${stdout}`;
            } else {
                const { stdout } = await execAsync('ps aux --sort=-%mem | head -10');
                processInfo = `内存占用前10的进程:\n${stdout}`;
            }
        } catch (error) {
            processInfo = `无法获取进程信息: ${error.message}`;
        }

        return {
            content: [
                {
                    type: 'text',
                    text: `系统监控报告:
          
CPU信息:
- 型号: ${cpuInfo[0].model}
- 核心数: ${cpuInfo.length}
- 速度: ${cpuInfo[0].speed} MHz

内存信息:
- 总内存: ${(totalMem / 1024 / 1024 / 1024).toFixed(2)} GB
- 已用内存: ${(usedMem / 1024 / 1024 / 1024).toFixed(2)} GB
- 空闲内存: ${(freeMem / 1024 / 1024 / 1024).toFixed(2)} GB
- 内存使用率: ${memUsage}%

${diskInfo}

${processInfo}

操作系统:
- 平台: ${process.platform}
- 版本: ${os.release()}
- 主机名: ${os.hostname()}
- 上线时间: ${(os.uptime() / 3600).toFixed(2)} 小时
`,
                },
            ],
        };
    }

    async analyzeDependencies(projectPath, packageManager) {
        // 检查项目路径是否存在
        try {
            await fs.access(projectPath);
        } catch (error) {
            throw new McpError(
                ErrorCode.InvalidParams,
                `项目路径不存在: ${projectPath}`
            );
        }

        // 自动检测包管理器
        if (packageManager === 'auto') {
            try {
                const files = await fs.readdir(projectPath);
                if (files.includes('package.json')) {
                    packageManager = files.includes('yarn.lock') ? 'yarn' : 'npm';
                } else if (files.includes('requirements.txt')) {
                    packageManager = 'pip';
                } else {
                    throw new McpError(
                        ErrorCode.InvalidParams,
                        '无法自动检测包管理器，请指定 package_manager 参数'
                    );
                }
            } catch (error) {
                throw new McpError(
                    ErrorCode.InternalError,
                    `读取项目目录失败: ${error.message}`
                );
            }
        }

        // 分析依赖
        let result;
        try {
            switch (packageManager) {
                case 'npm':
                    result = await this.analyzeNpmDependencies(projectPath);
                    break;
                case 'yarn':
                    result = await this.analyzeYarnDependencies(projectPath);
                    break;
                case 'pip':
                    result = await this.analyzePipDependencies(projectPath);
                    break;
                default:
                    throw new McpError(
                        ErrorCode.InvalidParams,
                        `不支持的包管理器: ${packageManager}`
                    );
            }
        } catch (error) {
            throw new McpError(
                ErrorCode.InternalError,
                `分析依赖失败: ${error.message}`
            );
        }

        return {
            content: [
                {
                    type: 'text',
                    text: result,
                },
            ],
        };
    }

    async analyzeNpmDependencies(projectPath) {
        try {
            // 检查过时的包
            const { stdout: outdatedOutput } = await execAsync('npm outdated --json', { cwd: projectPath });
            const outdated = outdatedOutput.trim() ? JSON.parse(outdatedOutput) : {};

            // 检查安全漏洞
            const { stdout: auditOutput } = await execAsync('npm audit --json', { cwd: projectPath });
            const audit = auditOutput.trim() ? JSON.parse(auditOutput) : { vulnerabilities: {} };

            // 读取 package.json
            const packageJsonPath = path.join(projectPath, 'package.json');
            const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));

            // 构建报告
            let report = `## NPM 依赖分析报告\n\n`;

            // 依赖概览
            const dependencies = packageJson.dependencies || {};
            const devDependencies = packageJson.devDependencies || {};

            report += `### 依赖概览\n\n`;
            report += `- 生产依赖: ${Object.keys(dependencies).length} 个包\n`;
            report += `- 开发依赖: ${Object.keys(devDependencies).length} 个包\n\n`;

            // 过时的包
            const outdatedPackages = Object.keys(outdated);
            report += `### 过时的包 (${outdatedPackages.length})\n\n`;

            if (outdatedPackages.length > 0) {
                report += `| 包名 | 当前版本 | 最新版本 | 类型 |\n`;
                report += `| ---- | -------- | -------- | ---- |\n`;

                for (const pkg of outdatedPackages) {
                    const info = outdated[pkg];
                    report += `| ${pkg} | ${info.current} | ${info.latest} | ${info.type || '-'} |\n`;
                }
            } else {
                report += `所有包都是最新的！👍\n`;
            }

            report += `\n`;

            // 安全漏洞
            const vulnerabilities = audit.vulnerabilities || {};
            const vulnerabilityCount = Object.keys(vulnerabilities).length;

            report += `### 安全漏洞 (${vulnerabilityCount})\n\n`;

            if (vulnerabilityCount > 0) {
                report += `| 包名 | 严重程度 | 描述 | 修复建议 |\n`;
                report += `| ---- | -------- | ---- | -------- |\n`;

                for (const [pkg, info] of Object.entries(vulnerabilities)) {
                    report += `| ${pkg} | ${info.severity} | ${info.title || '-'} | ${info.recommendation || '更新到最新版本'} |\n`;
                }

                report += `\n运行 \`npm audit fix\` 修复可自动修复的漏洞。\n`;
            } else {
                report += `未发现安全漏洞！👍\n`;
            }

            return report;
        } catch (error) {
            return `分析 NPM 依赖失败: ${error.message}`;
        }
    }

    async analyzeYarnDependencies(projectPath) {
        try {
            // 检查过时的包
            const { stdout: outdatedOutput } = await execAsync('yarn outdated --json', { cwd: projectPath });
            const outdatedLines = outdatedOutput.trim().split('\n').filter(line => line.startsWith('{'));
            const outdated = outdatedLines.map(line => JSON.parse(line));

            // 读取 package.json
            const packageJsonPath = path.join(projectPath, 'package.json');
            const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 